#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
时间目录功能测试脚本
"""

import requests
import json
from datetime import datetime
import time

class TimeDirectoryTester:
    def __init__(self, base_url, username, password):
        self.base_url = base_url.rstrip('/')
        self.username = username
        self.password = password
        self.session = requests.Session()
        self.session.auth = (username, password)
        self.test_results = []
        
    def log_test(self, test_name, success, message, details=None):
        """记录测试结果"""
        result = {
            'test_name': test_name,
            'success': success,
            'message': message,
            'timestamp': datetime.now().isoformat(),
            'details': details or {}
        }
        self.test_results.append(result)
        
        status = "✅" if success else "❌"
        print(f"{status} {test_name}: {message}")
        if details:
            for key, value in details.items():
                print(f"   {key}: {value}")
    
    def test_file_upload_with_time_dir(self):
        """测试文件上传到时间目录"""
        test_file = "time_dir_test.txt"
        test_content = f"时间目录测试文件 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        
        try:
            # 上传文件
            response = self.session.put(f"{self.base_url}/dav/{test_file}", data=test_content)
            upload_success = response.status_code in [200, 201, 204]
            
            # 下载文件验证
            response = self.session.get(f"{self.base_url}/dav/{test_file}")
            download_success = response.status_code == 200 and response.text == test_content
            
            # 删除文件
            response = self.session.delete(f"{self.base_url}/dav/{test_file}")
            delete_success = response.status_code in [200, 204]
            
            success = upload_success and download_success and delete_success
            
            self.log_test("时间目录文件上传测试", success, 
                         f"上传: {upload_success}, 下载: {download_success}, 删除: {delete_success}", {
                'upload_status': response.status_code if upload_success else 'failed',
                'download_status': response.status_code if download_success else 'failed',
                'delete_status': response.status_code if delete_success else 'failed',
                'file_content_length': len(test_content)
            })
            return success
            
        except Exception as e:
            self.log_test("时间目录文件上传测试", False, f"操作失败: {e}")
            return False
    
    def test_multiple_files_upload(self):
        """测试多个文件上传"""
        test_files = [
            ("test_file_1.txt", "第一个测试文件"),
            ("test_file_2.txt", "第二个测试文件"),
            ("中文文件.txt", "中文测试文件"),
            ("test_file_3.txt", "第三个测试文件")
        ]
        
        try:
            upload_results = []
            download_results = []
            delete_results = []
            
            # 上传所有文件
            for filename, content in test_files:
                response = self.session.put(f"{self.base_url}/dav/{filename}", data=content)
                upload_results.append(response.status_code in [200, 201, 204])
            
            # 下载所有文件验证
            for filename, content in test_files:
                response = self.session.get(f"{self.base_url}/dav/{filename}")
                download_results.append(response.status_code == 200 and response.text == content)
            
            # 删除所有文件
            for filename, content in test_files:
                response = self.session.delete(f"{self.base_url}/dav/{filename}")
                delete_results.append(response.status_code in [200, 204])
            
            upload_success = all(upload_results)
            download_success = all(download_results)
            delete_success = all(delete_results)
            
            success = upload_success and download_success and delete_success
            
            self.log_test("多文件时间目录测试", success, 
                         f"上传: {upload_success}, 下载: {download_success}, 删除: {delete_success}", {
                'total_files': len(test_files),
                'upload_success_count': sum(upload_results),
                'download_success_count': sum(download_results),
                'delete_success_count': sum(delete_results)
            })
            return success
            
        except Exception as e:
            self.log_test("多文件时间目录测试", False, f"操作失败: {e}")
            return False
    
    def test_server_connection(self):
        """测试服务器连接"""
        try:
            response = self.session.get(f"{self.base_url}/")
            success = response.status_code == 200
            self.log_test("服务器连接测试", success, f"状态码: {response.status_code}")
            return success
        except Exception as e:
            self.log_test("服务器连接测试", False, f"连接失败: {e}")
            return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print("🚀 开始时间目录功能测试")
        print("=" * 80)
        print(f"测试目标: {self.base_url}/dav")
        print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 80)
        
        start_time = time.time()
        
        # 运行测试
        tests = [
            self.test_server_connection,
            self.test_file_upload_with_time_dir,
            self.test_multiple_files_upload
        ]
        
        passed = 0
        for test in tests:
            if test():
                passed += 1
        
        duration = time.time() - start_time
        
        # 输出结果
        print("\n" + "=" * 80)
        print("📊 测试结果汇总")
        print("=" * 80)
        print(f"总测试数: {len(tests)}")
        print(f"通过测试: {passed}")
        print(f"失败测试: {len(tests) - passed}")
        print(f"成功率: {passed/len(tests)*100:.1f}%")
        print(f"测试耗时: {duration:.2f}秒")
        
        # 保存报告
        report = {
            'total': len(tests),
            'passed': passed,
            'failed': len(tests) - passed,
            'success_rate': passed/len(tests)*100,
            'duration': duration,
            'results': self.test_results
        }
        
        report_file = f"test/time_directory_test_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        
        print(f"\n📄 详细测试报告已保存到: {report_file}")
        
        return passed == len(tests)

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='时间目录功能测试')
    parser.add_argument('--host', default='127.0.0.1', help='服务器地址')
    parser.add_argument('--port', default='8083', help='服务器端口')
    parser.add_argument('--username', default='testuser', help='用户名')
    parser.add_argument('--password', default='testpass123', help='密码')
    
    args = parser.parse_args()
    
    base_url = f"http://{args.host}:{args.port}"
    
    tester = TimeDirectoryTester(base_url, args.username, args.password)
    success = tester.run_all_tests()
    
    exit(0 if success else 1)
